#include "Thread.h"

static thread_local unsigned long int s_tid = 0;
static thread_local std::string s_strName = "";

namespace utils
{

Thread::Thread(std::function<void()> task, const std::string& name)
    : m_strName(name)
    , m_task(task)
{
    ::pthread_create(&m_id, nullptr, &run, this);
    m_sem.wait();
}

Thread::~Thread()
{
    ::pthread_detach(m_id);
}

void Thread::join()
{
    ::pthread_join(m_id, nullptr);
}

unsigned long int Thread::getId()
{
    return s_tid;
}

std::string Thread::getName()
{
    return s_strName;
}

void* Thread::run(void* arg)
{
    Thread* th = (Thread*)arg;
    s_strName = th->m_strName; 
    s_tid = th->m_id;
    ::pthread_setname_np(pthread_self(), th->m_strName.c_str());
    std::function<void()> task;
    std::swap(task, th->m_task);

    th->m_sem.notify();

    task();
    return nullptr;
}
    
} // namespace utils
